<?php


if (!function_exists('curl_init')) {
  throw new Exception('This class needs the CURL PHP extension.');
}
if (!function_exists('json_decode')) {
  throw new Exception('This class needs the JSON PHP extension.');
}

class Twitter{

	private $key = "";
	private $secret = "";
	private $token = "";
	
	function __construct($key, $secret) {  

		$this->key = $key;            
		$this->secret = $secret;  
		$this->token = $this->getToken($key, $secret);

	}


	private function getToken($_key, $_secret){

		$oauth_path = "https://api.twitter.com/oauth2/token";
		$pair = $_key.":".$_secret;
		$pair64 = base64_encode($pair);

		$curl_oauth = curl_init($oauth_path);
		curl_setopt($curl_oauth, CURLOPT_POST, 1);
		curl_setopt($curl_oauth, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
		curl_setopt($curl_oauth, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded;charset=UTF-8;","Authorization: Basic ".$pair64));
		curl_setopt($curl_oauth, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl_oauth, CURLOPT_SSL_VERIFYPEER, in_array($_SERVER['HTTP_HOST'], array("localhost","127.0.0.1")) ? false : true);
		$response = curl_exec($curl_oauth);

		curl_close($curl_oauth);


		//Testa erro no curl
		if($response == false){
			return false;
		}

		//Checa retorno json. Melhorar notificações de erro.
		$response_decoded = json_decode($response, true);

		if (isset($response_decoded["errors"])){
			return false;
		}

		//Se pegou token, retorna
		if(isset($response_decoded["access_token"])){
			return $response_decoded["access_token"];
		}

		return false;
	}


	public function api($_url){

		if($this->token==""){
			return false;
		}

		$curl_api = curl_init($_url);
		curl_setopt($curl_api, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded;charset=UTF-8;","Authorization: Bearer ".$this->token));
		curl_setopt($curl_api, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl_api, CURLOPT_SSL_VERIFYPEER, in_array($_SERVER['HTTP_HOST'], array("localhost","127.0.0.1")) ? false : true);
		$api_response = curl_exec($curl_api);

		curl_close($curl_api);


		//Testa erro no curl
		if($api_response == false){
			return false;
		}

		//Testa erro no retorno json
		$api_response_decoded = json_decode($api_response, true);
		if (isset($api_response_decoded["errors"])){
			return false;
		}else{
			return $api_response_decoded;
		}

		


	}











}

?>